package com.nami.store.biz.user.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nami.store.api.request.user.UserAddRequest;
import com.nami.store.api.response.user.UserDTO;
import com.nami.store.biz.user.convert.UserConvert;
import com.nami.store.biz.user.repository.UserRepository;
import com.nami.store.domain.UserDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserDomainService {

    private final UserRepository userRepository;


    public UserDTO getUserById(String appKey, String userId) {
        UserDO user = userRepository.getUserById(appKey, userId);
        return UserConvert.INSTANCE.convert(user);
    }

    public void updateUserById(UserDO user) {
        userRepository.updateUserById(user);
    }

    public Boolean saveUser(UserDO user) {
        user.setDelFlag("0");
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userRepository.saveUser(user);
        log.info("[user-save] 注册用户：{}", ToStringBuilder.reflectionToString(user, ToStringStyle.SHORT_PREFIX_STYLE));
        return Boolean.TRUE;
    }

    public boolean batchSave(List<UserAddRequest> users) {
        return userRepository.batchSave(UserConvert.INSTANCE.convertList2(users));
    }

    public UserDTO getUserByMobile(String mobile) {
        UserDO user = userRepository.getUserByMobile(mobile);
        if (ObjectUtil.isNull(user)) {
            return null;
        }
        return UserConvert.INSTANCE.convert(user);

    }

    public Map<String, UserDTO> getUsersByIds(List<String> userIds) {
        List<UserDTO> list = this.getUserByIds(userIds);
        if (CollUtil.isEmpty(userIds)) {
            return new HashMap<>();
        }
        return list.stream().collect(Collectors.toMap(UserDTO::getUserId, Function.identity()));
    }

    public UserDTO getUserByUserId(String userId) {
        UserDO user = userRepository.getUserByUserId(userId);
        if (user == null) {
            return null;
        }

        return UserConvert.INSTANCE.convert(user);
    }

    public List<UserDTO> getUserByIds(List<String> userIds) {
        List<UserDO> userByIds = userRepository.getUserByIds(userIds);
        return UserConvert.INSTANCE.convertList(userByIds);
    }

    public UserDO getUserByAccount(String account) {

        return null;
    }

}
